package com.jinbai.servlet.album;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinbai.data_object.AlbumDO;
import com.jinbai.repo.AlbumRepo;
import com.jinbai.util.Log;
import com.jinbai.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebFault;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/studio/album/list.json")
public class ListJsonServlet extends HttpServlet {
    private final AlbumRepo albumRepo = new AlbumRepo();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        final HttpSession session = req.getSession(false);
        UserVO userVO = null;
        if (session != null) {
            userVO = (UserVO) session.getAttribute("currentUser");
        }
        if (userVO == null) {
            Log.println("用户未登录");
            resp.sendRedirect("/studio/user/login.html");
            return;
        }
        List<AlbumDO> albumDOList = albumRepo.selectAlbumsByUid(userVO.getUid());
        final String json = objectMapper.writeValueAsString(albumDOList);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        final PrintWriter writer = resp.getWriter();
        writer.println(json);
    }
}
